﻿using Abp.Domain.Repositories;
using Paas.Core;
using Microsoft.EntityFrameworkCore;
using Basefr.Attributes;
using Basefr.Data.EntityFrameworkCore;
using System;
using System.Linq;
using System.Reflection;

namespace Paas.Infrastructure.Data.EntityFrameworkCore
{
    [AutoRepositoryTypes(typeof(IMainRepository<>), typeof(IMainRepository<,>), typeof(MainRepository<>), typeof(MainRepository<,>), WithDefaultRepositoryInterfaces = true)]
    public class MainDbContext : DbContext<MainDbContext>
    {
        public MainDbContext(DbContextOptions<MainDbContext> options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //将实体类型添加到DbContext
            var entityTpyes = AppDomain.CurrentDomain.GetAssemblies()
                .Where(a => !a.IsDynamic)
                .SelectMany(p => p.ExportedTypes)
                .Where(t => t.GetCustomAttribute<MainTableAttribute>() != null)
                .ToList();

            entityTpyes.ForEach(type => modelBuilder.Entity(type));

            //禁止级联删除
            modelBuilder.Model.GetEntityTypes()
                .SelectMany(t => t.GetForeignKeys())
                .Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade)
                .ToList().ForEach(fk => fk.DeleteBehavior = DeleteBehavior.ClientSetNull);

            base.OnModelCreating(modelBuilder);
        }
    }
}

